import 'package:flutter/material.dart';
import '../models/friend_model.dart';
import '../repositories/friend_repository.dart';
import '../repositories/chat_repository.dart';
import '../errors/error_handler.dart';
import '../services/error_logger_service.dart';

class HomeViewModel extends ChangeNotifier {
  final FriendRepository _friendRepository;

  HomeViewModel(this._friendRepository, ChatRepository chatRepository);

  bool _isLoading = false;
  String? _errorMessage;
  List<FriendModel> _recentContacts = [];

  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  List<FriendModel> get recentContacts => _recentContacts;
  bool get hasError => _errorMessage != null;

  /// 加载首页数据（最近联系人）
  Future<void> loadRecentContacts() async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      // 获取好友列表作为最近联系人（实际应该根据最近聊天记录）
      final response = await _friendRepository.getFriends();

      _isLoading = false;

      if (response.success && response.data != null) {
        // 只显示已同意的好友（status = 1）
        _recentContacts = response.data!
            .where((friend) => friend.status == 1)
            .toList();
        _errorMessage = null;
      } else {
        _errorMessage = response.message;
        _recentContacts = [];
      }
      notifyListeners();
    } catch (e) {
      _isLoading = false;
      _errorMessage = ErrorHandler.getErrorMessage(e);
      _recentContacts = [];
      ErrorLoggerService.logError(e, context: 'LoadRecentContacts');
      notifyListeners();
    }
  }

  /// 刷新数据
  Future<void> refresh() async {
    await loadRecentContacts();
  }

  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  /// 清理所有数据（退出登录时调用）
  void clear() {
    _recentContacts = [];
    _errorMessage = null;
    _isLoading = false;
    notifyListeners();
  }
}

